from typing import Annotated, List

from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.requests import Request

from app.core import dependencies
from app.db import session
from app.db.models import user as user_model
from app.schemas import image as image_schema
from app.services import image_gen as image_service
from app.utils.rate_limiter import user_limiter

router = APIRouter(prefix="/images", tags=["Images"])

@router.post("/generate", response_model=image_schema.ImageGenerateResponse)
@user_limiter.limit("5/minute")
async def generate_image_endpoint(
    request_payload: image_schema.ImageGenerateRequest,
    request: Request,
    current_user: Annotated[user_model.User, Depends(dependencies.get_current_user)],
    db: Annotated[AsyncSession, Depends(session.get_db)]
):
    """Submit a prompt to generate an image. Deducts 1 credit."""
    try:
        image_url, history_id = await image_service.generate_image_and_log(
            db=db,
            user_id=current_user.id,
            prompt=request_payload.prompt
            # generation_cost could be added if variable costs are needed
        )
        return image_schema.ImageGenerateResponse(image_url=image_url, history_id=history_id)
    except HTTPException as e:
        # Service layer handles specific errors (credits, API), just re-raise
        raise e
    except Exception as e:
        # Catch any unexpected errors from the service layer
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Image generation failed unexpectedly.")

@router.get("/history", response_model=List[image_schema.ImageHistory])
async def get_image_history_endpoint(
    current_user: Annotated[user_model.User, Depends(dependencies.get_current_user)],
    db: Annotated[AsyncSession, Depends(session.get_db)],
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=200)
):
    """Get the current user's image generation history."""
    history = await image_service.get_user_image_history(
        db=db, user_id=current_user.id, skip=skip, limit=limit
    )
    return history

@router.delete("/history/{history_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_history_entry_endpoint(
    history_id: int,
    current_user: Annotated[user_model.User, Depends(dependencies.get_current_user)],
    db: Annotated[AsyncSession, Depends(session.get_db)]
):
    """(Soft) delete an entry from the user's image generation history."""
    success = await image_service.delete_image_history_entry(
        db=db, user_id=current_user.id, history_id=history_id
    )
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="History entry not found or already deleted."
        )
    # No content returned on successful deletion
    return None
